<?php 
require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

function reservationCount( $dbConnection, $customerId, $reservationDate, & $resCount )
{
    global $enum;
    try
    {
        $statement = $dbConnection->prepare( "SELECT COUNT(1) AS rescount FROM reservations WHERE customerid = ? AND reservationdate = ? AND reservationtype = ?" );
        $statement->bindParam( 1, $customerId, PDO::PARAM_INT );
        $statement->bindParam( 2, $reservationDate, PDO::PARAM_STR );
        $statement->bindParam( 3, $enum['RESERVATION_TYPE_RESERVATION'], PDO::PARAM_INT );
        $statement->execute();
        
        $result = $statement->fetchAll( PDO::FETCH_OBJ );
        if (! $result)
            return false;
        
        $resCount = $result[0]->rescount;
        return true;
    } 
    catch (PDOException $e)
    {
        return false;
    }

    return true;
}
function insertReservation( $loggedUser, $reservationDate, $courtNumber, $timeNumber, & $errorStr )
{
    global $enum;

    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
        return false;
    
    $resCount = 0;
    if (! reservationCount( $dbConnection, $loggedUser->id, $reservationDate, $resCount ))
    {
        $errorStr = isEnglish() ? "Database error" : "Chyba v databáze";
        return false;
    }
    
    if ($resCount >= 2)
    {
        $errorStr = isEnglish() ? "It is possible to make at the most two reservations per day through the web." : "Cez web je možné spraviť na jeden deň rezerváciu najviac na dve hodiny.";
        return false;
    }   

    $description = "";
    try
    {
        $statement = $dbConnection->prepare( "INSERT INTO reservations( customerid, courtnumber, reservationdate, timenumber, reservationtype, description, ipaddress ) VALUES( ?, ?, ?, ?, ?, ?, ? )" );

        $statement->bindParam( 1, $loggedUser->id, PDO::PARAM_INT );
        $statement->bindParam( 2, $courtNumber, PDO::PARAM_INT );
        $statement->bindParam( 3, $reservationDate, PDO::PARAM_STR );
        $statement->bindParam( 4, $timeNumber, PDO::PARAM_INT );
        $statement->bindParam( 5, $enum['RESERVATION_TYPE_RESERVATION'], PDO::PARAM_INT );
        $statement->bindParam( 6, $description, PDO::PARAM_STR );
        $statement->bindParam( 7, $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR );

        $statement->execute();
    }
    catch(PDOException $e)
    {
        $code = $e->getCode();
        if ($code == 23505)
        {
            $errorStr = isEnglish() ? "The term is already reserved" : "Termín je už rezervovaný";
        }
        else
        {
            $errorStr = isEnglish() ? "Database error" : "Chyba v databáze $code";
        }
        
        return false;
    }

    // poslem mail, ze je rezervovany
    $db->commit();
    $c = $courtNumber + 1;
    WebStat::logReservationDone( $loggedUser->emailAddress, $reservationDate, $courtNumber, $timeNumber );
    logInfo( "Reservation done - date|$reservationDate;time|$timeNumber;court|$c;user|$loggedUser->emailAddress", LOG_INFO_RESERVATION_DONE );
    return true;
}

function isPossibleToCancelTheReservation( $reservationDate, $timeNumber, & $errorStr )
{
    $myDateTime = MyDateTime::fromPqDate( $reservationDate );
    if ( ( ( 24 - $timeNumber ) * 3600 ) >= ( $myDateTime->timeStamp() - time() ))
    {
        $errorStr = isEnglish() ? "Less than 24 hours before reserved term is not possible to cancel the reservation through the web." : "Menej ako 24 hodín pred rezervovaným termínom nie je možné zrušiť rezerváciu cez web.";
        return false;
    }
    
    return true;
}

function cancelReservation( $loggedUser, $reservationDate, $courtNumber, $timeNumber, & $errorStr )
{
    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
        return false;
    
    try
    {
        $statement = $dbConnection->prepare( "SELECT tournamentid, reservationtype, description, ipaddress FROM reservations WHERE customerid = ? AND reservationdate = ? AND courtnumber = ? AND timenumber = ?");

        $statement->bindParam( 1, $loggedUser->id, PDO::PARAM_INT );
        $statement->bindParam( 2, $reservationDate, PDO::PARAM_STR );
        $statement->bindParam( 3, $courtNumber, PDO::PARAM_INT );
        $statement->bindParam( 4, $timeNumber, PDO::PARAM_INT );
        
        $statement->execute();
        $result = $statement->fetch( PDO::FETCH_OBJ );
        if (! $result)
            return false;
        
        $userName = $loggedUser->name . " " . $loggedUser->surname;
        $description = "";
        // cancel by the web
        $reservationCancelReason = 5;
        $statement = $dbConnection->prepare( "INSERT INTO deletedreservations ( customerid, userid, tournamentid, username, courtnumber, reservationdate, timenumber, reservationtype, description, ipaddress, reservationcancelreason, deletingdescription, dateofdeletion ) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now() )" );
        $statement->bindParam( 1, $loggedUser->id, PDO::PARAM_INT );
        $statement->bindParam( 2, $loggedUser->id, PDO::PARAM_INT );
        $statement->bindParam( 3, $result->tournamentid, is_null( $result->tournamentid ) ? PDO::PARAM_NULL : PDO::PARAM_INT );
        $statement->bindParam( 4, $userName, PDO::PARAM_STR );
        $statement->bindParam( 5, $courtNumber, PDO::PARAM_INT );
        $statement->bindParam( 6, $reservationDate, PDO::PARAM_STR );
        $statement->bindParam( 7, $timeNumber, PDO::PARAM_INT );
        $statement->bindParam( 8, $result->reservationtype, PDO::PARAM_INT );
        $statement->bindParam( 9, $description, PDO::PARAM_STR );
        $statement->bindParam( 10, $result->ipaddress, is_null( $result->ipaddress ) ? PDO::PARAM_NULL : PDO::PARAM_STR );
        $statement->bindParam( 11, $reservationCancelReason, PDO::PARAM_INT );
        $statement->bindParam( 12, $description, PDO::PARAM_STR );
        
        $statement->execute();
        
        $statement = $dbConnection->prepare( "DELETE FROM reservations WHERE customerid = ? AND reservationdate = ? AND courtnumber = ? AND timenumber = ?");

        $statement->bindParam( 1, $loggedUser->id, PDO::PARAM_INT );
        $statement->bindParam( 2, $reservationDate, PDO::PARAM_STR );
        $statement->bindParam( 3, $courtNumber, PDO::PARAM_INT );
        $statement->bindParam( 4, $timeNumber, PDO::PARAM_INT );
        
        $statement->execute();
    }
    catch(PDOException $e)
    {
        $code = $e->getCode();
        if ($code == 23505)
        {
            $errorStr = isEnglish() ? "The term is already reserved" : "Termín je už rezervovaný";
        }
        else
        {
            $errorStr = isEnglish() ? "Database error" : "Chyba v databáze $code";
        }
        
        return false;
    }

    // poslem mail, ze bola zrusena rezervacia
    $db->commit();
    $c = $courtNumber + 1;
    WebStat::logReservationCanceled( $loggedUser->emailAddress, $reservationDate, $courtNumber, $timeNumber );
    logInfo( "Reservation canceled - date|$reservationDate;time|$timeNumber;court|$c;user|$loggedUser->emailAddress", LOG_INFO_RESERVATION_CANCELED );
    return true;
}

if (! isset( $_SESSION[ 'logged_user' ] ))
    exit;

if (! isset( $_GET[ 'confirmReservation' ] ))
    exit;

if (! isset( $_GET[ 'reservationDate' ] ))
    exit;

if (! isset( $_GET[ 'courtNumber' ] ))
    exit;

if (! isset( $_GET[ 'timeNumber' ] ))
    exit;

$reservationDate = $_GET[ 'reservationDate' ];
$courtNumber = $_GET[ 'courtNumber' ];
$timeNumber = $_GET[ 'timeNumber' ];
$confirmReservation = $_GET[ 'confirmReservation' ];
$loggedUser = unserialize( $_SESSION[ 'logged_user' ] );

$errorStr = "";
if ($confirmReservation)
{
    if (insertReservation( $loggedUser, $reservationDate, $courtNumber, $timeNumber, $errorStr ))
    {
        $headerStr = "location: ../index.php?siteName=mainsites/reservation.php&reservationDate=$reservationDate";
        header( $headerStr );
        exit;
    }
}
else
{   
    if (isPossibleToCancelTheReservation( $reservationDate, $timeNumber, $errorStr ))
    {
        if (cancelReservation($loggedUser, $reservationDate, $courtNumber, $timeNumber, $errorStr))
        {
            $headerStr = "location: ../index.php?siteName=mainsites/reservation.php&reservationDate=$reservationDate";
            header( $headerStr );
            exit;
        }
    }
}
        
showError( $errorStr );

?>
